<!--TODO: 登录&注册页面，需要添加注册功能 -->
<template>
    <div>
        <el-card class="login-form-layout">
            <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
                <!--        <div style="text-align: center">-->
                <!--          <svg-icon icon-class="login-mall" style="width: 56px;height: 56px;color: #409EFF"></svg-icon>-->
                <!--        </div>-->
                <h2 class="login-title color-main">HUST线上二手市场</h2>
                <!-- 下面这一组件在文本框中显示 输入用户名       -->
                <el-form-item prop="username">
                    <el-input name="username"
                              type="text"
                              v-model="loginForm.username"
                              autoComplete="on"
                              placeholder="请输入用户名">
          <span slot="prefix">
            <svg-icon icon-class="user" class="color-main"></svg-icon>
          </span>
                    </el-input>
                </el-form-item>
                <!--下面这一组件在输入密码的文本框中显示 请输入密码-->
                <el-form-item prop="password">
                    <el-input name="password"
                              type="password"
                              @keyup.enter.native="handleLogin"
                              v-model="loginForm.password"
                              autoComplete="on"
                              placeholder="请输入密码">
          <span slot="prefix">
            <svg-icon icon-class="password" class="color-main"></svg-icon>
          </span>
                    </el-input>
                </el-form-item>
                <!--          显示两种用户类型的选项-->
                <el-form-item prop="userType">
                    <el-radio-group v-model="loginForm.userType">
                        <el-radio :label="UserType.student">普通用户</el-radio>
                        <el-radio :label="UserType.admin">管理员</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!--          -->
                <el-form-item style="margin-bottom: 60px;text-align: center">
                    <el-button style="width: 100%" type="primary" :loading="loading" @click.native.prevent="handleLogin">
                        登录
                    </el-button>

                </el-form-item>
                <el-form-item style="margin-bottom: 60px;text-align: center">
                    <!--            下面是一个注册连接-->
                    <router-link to="" @click.native.prevent="toRegister">
                        <span style="color: #00abff" class="a-inner"><i class="el-icon-edit"></i> 点击进行注册 </span>
                    </router-link>
                </el-form-item>


            </el-form>
        </el-card>
        <img :src="bg" class="login-center-layout">
    </div>
</template>

<script>
import {isvalidUsername} from "../../utils/validate";
import UserType from "../../common/userType";
import bg from '../../assets/bg.jpg'
import store from "../../store";
import router from "../../router";
import {getUserInfo} from "../../api/login";


export default {
    name: 'login',
    data() {
        const validateUsername = (rule, value, callback) => {
            if (!isvalidUsername(value)) {
                callback(new Error("请输入正确的用户名！"))
            } else {
                callback();
            }
        };

        const validatePwd = (rule, value, callback) => {
            if (value.length < 3) {
                callback(new Error("密码的长度不能小于3!"))
            } else {
                callback();
            }
        };

        const validateUserType = (rule, value, cb) => {
            if ([UserType.admin, UserType.student, UserType.teacher].indexOf(value) === -1) {
                cb(new Error('用户身份错误！'))
            } else {
                cb();
            }
        }

        return {
            bg: bg,
            UserType,
            loginForm: {
                username: '',
                password: '',
                userType: UserType.student
            },
            loginRules: {
                username: [{ required: true, message: "请输入用户名", trigger: "blur", validator: validateUsername}],
                password: [{ required: true, message: "请输入密码", trigger: "blur", validator: validatePwd}],
                userType: [{ required: true, message: "请选择用户类型", trigger: "blur", validator: validateUserType}]
            },
            loading: false,
        };
    },
    created() {
        // 尝试从本地加载上次登陆的账号
        this.loginForm.username = localStorage.getItem("username");
        this.loginForm.password = localStorage.getItem("password");
        this.loginForm.userType = parseInt(localStorage.getItem("userType"));

        if (!this.loginForm.username) {
            this.loginForm.username = ''; // 默认是学生账号
        }
        if(!this.loginForm.password) {
            this.loginForm.password = '';
        }
        if (!this.loginForm.userType) {
            this.loginForm.userType = parseInt(UserType.student);
        }
    },
    methods: {
        toRegister() {
            this.$router.push({path: '/user/signup'});
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$store.dispatch('Login', this.loginForm).then( () => {
                        this.loading = false;
                        localStorage.setItem("username", this.loginForm.username);
                        localStorage.setItem("password", this.loginForm.password);
                        localStorage.setItem("userType", this.loginForm.userType);

                        //登录成功后添加可访问的路由表
                        getUserInfo().then(res => {
                            let menus = res.data.menus || [];
                            store.dispatch("GenerateRouters", {menus}).then(() => {
                                router.addRoutes(store.getters.addRouters);
                                this.$router.push({path: '/'});
                            })
                        })
                    }).catch((error) => {
                        this.loading = false;
                    })
                }
                else {
                    console.log("登陆参数校验不合法！");
                    return false;
                }
            })
        },
    }
};
</script>

<style scoped>
.login-form-layout {
    position: absolute;
    z-index: 99;
    left: 0;
    right: 0;
    width: 360px;
    margin: 140px auto;
    border-top: 10px solid #409EFF;
}

.login-title {
    text-align: center;
}

.login-center-layout {
    background: #409EFF;
    position: fixed;
    z-index: 10;
    width: 100%;
    height: 100%;
    max-width: 100%;
    max-height: 100%;
    /*margin-top: 200px;*/
}
</style>
